package com.mintyfresh.tns.util;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.util.*;

public class Player implements Serializable {
	private String username;
	private Pair location;
	private boolean isAgent;
	transient private ObjectOutputStream connection;
	transient private Terrain terrain;
	transient private Physics engine;
	transient private HashMap<String, Pair> players;

	public Player(
			String username,
			ObjectOutputStream connection,
			boolean isAgent)
	{
		this.username = username;
		this.connection = connection;
		this.isAgent = isAgent;
	}

	public ObjectOutputStream getConnection() {
		return connection;
	}

	public void setLocation(Pair p) {
		location = p;
	}
	public Pair getLocation() {
		return location;
	}

	public String getUsername() {
		return username;
	}

	public boolean isAgent() {
		return isAgent;
	}

	public Message send(Object o) {
		Message msg = (Message)o;
		if (msg.type().equals("connected")) {return null;}
		else if (msg.type().equals("badUsername")) {return null;}
		else if (msg.type().equals("newRound")) {
			return newRound(msg);}
		else if (msg.type().equals("signalPlayerTurn")) {
			return signalPlayerTurn(msg);}
		else if (msg.type().equals("shotResults")) {
			return shotResults(msg);}
		else if (msg.type().equals("endRound")) {return null;}
		else if (msg.type().equals("endGame")) {return null;}
		else return null;
	}

	private Message newRound(Message msg) {
		terrain = (Terrain)msg.get("terrain");
		engine = (Physics)msg.get("engine");
		players = (HashMap<String, Pair>)msg.get("players");
		return null;
	}

	private Message signalPlayerTurn(Message msg) {
		int power = 50;
		int angle = 45;
		Message shotMsg = new Message("shot");
		shotMsg.set("power", power);
		shotMsg.set("angle", angle);
		return shotMsg;
	}

	private Message shotResults(Message msg) {
		Pair origin = (Pair)msg.get("origin");
		int power = msg.geti("power");
		int angle = msg.geti("angle");
		engine.pairs(
				origin,
				power,
				angle,
				terrain);
		LinkedList<Pair> path = engine.list();
		Pair end = path.getLast();
		Stack<Pair> tanksToRemove = new Stack<Pair>();
		int x = (int)end.x;
		for(String player : players.keySet()) {
			Pair location = players.get(player);
			int X = (int)location.x;
			if(((x-40) <= X) && (X <= (x+40))) {
				players.remove(player);
			}
		}
		return null;
	}

	public String toString() {
		String s = new String();
		s += "Username: " + username + "\n";
		return s;
	}
}
